import Vue from 'vue'
import {ACCESS_TOKEN, USER_INFO} from '../store/mutation-types'

const ChatData = {
  mySocket: '',
  // 当前登陆人id
  userId: '',
  // 访问令牌
  accessToken: '',
  infoRandom: '',
  updateTime: new Date().valueOf(),
  // 新消息数量
  newsNum: 0,
  activeChatList: [
    {
      // 活跃聊天id
      chatActiveId: '',
      // 聊天室名称
      chatName: '',
      // 聊天室类型 f-好友聊天， g-群组聊天
      chatType: '',
      // 群id
      groupId: '',
      // 好友id
      friendId: '',
      // 群组类型
      groupType: '',
      // 接收状态
      receiveState: '',
      // 新消息数量
      newsNum: 0,
      // 头像地址
      avatar: '',
      // 头像缩略图地址
      avatarThumb: ''
    }
  ],
  // 当前聊天窗口id
  currentChatId: '',
  // 聊天信息map 活跃聊天id:[消息信息]
  chatInfoMap: {
    // 聊天室id
    // chatActiveId: [
    //   {
    //     // 发送用户id
    //     sendUserId: '',
    //     // 消息内容类型
    //     contentType: '',
    //     // 消息内容
    //     content: '',
    //     // 消息类型
    //     recordType: '',
    //     // 发送时间
    //     sendTime: '',
    //     // 状态 1-正常，2-撤回
    //     state: '',
    //     // 接收状态
    //     receiveState: '',
    //     // 接收用户id
    //     receiveUserId: '',
    //     // 接收时间
    //     receiveTime: '',
    //     // 群组id
    //     groupId: ''
    //   }
    // ]
  },
  // 用户id对应用户昵称及头像
  groupIdUserMap: {
    groupId: [{
      groupUserId: '',
      groupId: '',
      userId: '',
      nickname: '',
      userType: '',
      memberId: '',
      state: '',
      groupState: '',
      recordReadTime: ''
    }]
  },
  // 初始化ws
  initWebsocket () {
    const ws = Vue.prototype.baseConfig.chatWs
    console.log('ws', ws)
    if (ChatData.mySocket !== null && ChatData.mySocket !== undefined && ChatData.mySocket.readyState === WebSocket.OPEN) {
      return
    }
    ChatData.mySocket = new WebSocket(ws)
    ChatData.mySocket.onopen = ChatData.ws_onopen
    ChatData.mySocket.onerror = ChatData.ws_onerror
    ChatData.mySocket.onmessage = ChatData.ws_onmessage
    ChatData.mySocket.onclose = ChatData.ws_onclose
    let user = Vue.ls.get(USER_INFO)
    ChatData.accessToken = Vue.ls.get(ACCESS_TOKEN)
    ChatData.infoRandom = user.infoRandom
    ChatData.userId = user.userId
  },
  // 发送消息
  ws_send (chatMsg) {
    ChatData.checkDate()
    console.log('发送信息 >>>>', chatMsg)
    let sendContent = {
      accessToken: ChatData.accessToken,
      infoRandow: ChatData.infoRandom,
      ...chatMsg
    }
    ChatData.mySocket.send(JSON.stringify(sendContent))
  },
  // 接收消息
  ws_onmessage (e) {
    console.log('接收消息: ' + e.data)
    // 初次连接返回活跃聊天室列表
    let result = JSON.parse(e.data)
    if (!result.success) {
      ChatData.$message.error(result.message)
      return
    }
    if (result.code === 'recordType-1' || result.code === 'recordType-2') {
      // 1 群组消息
      // 2 好友消息
      let record = result.rows[0]
      let chatActiveId = ''
      let receiveUserId = ''
      if (record.recordType === 1) {
        chatActiveId = 'g' + record.groupId
      } else if (record.recordType === 2) {
        if (ChatData.userId === record.receiveUserId) {
          chatActiveId = 'f' + record.sendUserId
          receiveUserId = record.sendUserId
        } else if (ChatData.userId === record.sendUserId) {
          chatActiveId = 'f' + record.receiveUserId
          receiveUserId = record.receiveUserId
        }
      }
      if (!ChatData.chatInfoMap[chatActiveId]) {
        // 无数据 去请求历史数据
        let chatMsg = {
          recordType: 6,
          sendTime: '',
          groupId: record.groupId,
          receiveUserId: receiveUserId
        }
        ChatData.ws_send(chatMsg)
      }
      ChatData.updateChatInfoMap(record)
    } else if (result.code === 'recordType-3') {
      // 活跃列表消息
      ChatData.initActiveChat(result.rows)
    } else if (result.code === 'recordType-4') {
      // 获取群组用户消息
      if (result.rows) {
        let groupId = result.rows[0].groupId
        ChatData.groupIdUserMap[groupId] = result.rows
      }
    } else if (result.code === 'recordType-5') {
      // 获取群组用户消息
      if (result.rows) {
        let groupId = result.rows[0].groupId
        let chatActiveId = 'g' + groupId
        if (!groupId) {
          ChatData.updateChatInfoMap(result.rows[0])
          chatActiveId = 'f' + result.rows[0].sendUserId
        }
        ChatData.activeChatList.forEach(item2 => {
          if (item2.chatActiveId === chatActiveId) {
            ChatData.newsNum = ChatData.newsNum - item2.newsNum
            item2.newsNum = 0
          }
        })
      }
    } else if (result.code === 'recordType-6') {
      // 历史记录消息
      result.rows.forEach(item => {
        ChatData.updateChatInfoMap(item)
      })
    } else if (result.code === 'recordType-7') {
      // 历史记录消息]
      let num = 0
      result.rows.forEach(item => {
        ChatData.activeChatList.forEach(item2 => {
          if (item.chatActiveId === item2.chatActiveId) {
            item2.newsNum = item2.newsNum + item.newsNum
            num = num + item2.newsNum
          }
        })
      })
      ChatData.newsNum = ChatData.newsNum + num
    } else if (result.code === 'recordType-8') {
      // 群用户更新
      let groupUser = result.rows[0]
      let userList = ChatData.groupIdUserMap[groupUser.groupId]
      if (userList) {
        let has = false
        for (let i = 0; i < userList.length; i++) {
          if (userList[i].userId === groupUser.userId) {
            userList[i] = groupUser
            has = true
            break
          }
        }
        if (!has) {
          userList.push(groupUser)
        }
        ChatData.groupIdUserMap[groupUser.groupId] = userList
      }
    } else if (result.code === 'recordType-9') {
      // 群用户更新
      let group = result.rows[0]
      let chatList = ChatData.activeChatList
      if (chatList) {
        for (let i = 0; i < chatList.length; i++) {
          if (chatList[i].groupId === group.groupId) {
            chatList[i].chatName = group.groupName
            break
          }
        }
        ChatData.activeChatList = chatList
      }
    }
    ChatData.updateTime = new Date().valueOf()
  },
  ws_onopen () {
    console.log('连接服务器 成功...')
    console.log('发送初始连接信息！')
    let chatMsg = {
      recordType: 3,
      contentType: 1
    }
    ChatData.ws_send(chatMsg)
  },
  ws_onerror () {
    console.log('连接服务器 错误...')
  },
  ws_onclose () {
    console.log('连接服务器 关闭...')
  },
  out () {
    console.log('主动退出')
    ChatData.mySocket.close()
    ChatData.activeChatList = []
    ChatData.chatInfoMap = {}
    ChatData.currentChatId = ''
    ChatData.updateTime = ''
    ChatData.userId = ''
    ChatData.groupIdUserMap = ''
  },
  // 初始化活跃聊天室
  initActiveChat (activeChatList) {
    for (let chat of activeChatList) {
      if (chat.friendId === ChatData.userId) {
        let user = Vue.ls.get(USER_INFO)
        if (user.avatar) {
          chat.avatar = user.avatar
          chat.avatarThumb = user.avatarThumb
        }
      }
    }
    ChatData.activeChatList = []
    ChatData.activeChatList = activeChatList
  },
  // 添加新的活跃聊天室
  setNewActiveChatList (chat) {
    let chatActiveId = chat.chatActiveId
    let activeChatList = ChatData.activeChatList
    let activeList = [{
      // 活跃聊天id
      chatActiveId: chat.chatActiveId,
      // 聊天室名称
      chatName: chat.chatName,
      // 群id
      groupId: '',
      // 好友id
      friendId: chat.friendId,
      // 群组类型
      groupType: '',
      // 接收状态
      receiveState: ''
    }]
    for (let i = 0; i < activeChatList.length; i++) {
      if (activeChatList[i].chatActiveId !== chatActiveId) {
        activeList.push(activeChatList[i])
      } else {
        activeList[0] = activeChatList[i]
      }
    }
    ChatData.activeChatList = activeList
    ChatData.currentChatId = chatActiveId
    ChatData.updateTime = new Date().valueOf()
  },
  // 更新聊天信息数据 撤销\已读状态更新
  updateChatInfoMap (record) {
    ChatData.checkDate()
    // 获取活跃聊天室id
    let chatActiveId = ''
    if (record.recordType === 1) {
      chatActiveId = 'g' + record.groupId
    } else if (record.recordType === 2) {
      if (ChatData.userId === record.receiveUserId) {
        chatActiveId = 'f' + record.sendUserId
        record.friendId = record.sendUserId
      } else if (ChatData.userId === record.sendUserId) {
        chatActiveId = 'f' + record.receiveUserId
        record.friendId = record.receiveUserId
      } else {
        console.log('不是我的消息！')
        console.log('ChatData.userId', ChatData.userId)
        console.log('record.sendUserId', record.sendUserId)
        console.log('record.receiveUserId', record.receiveUserId)
        return
      }
    }
    record.chatActiveId = chatActiveId
    // 更新活跃聊天室顺序
    ChatData.updateActiveList(record)
    // 更新消息记录
    let infoList = ChatData.chatInfoMap[chatActiveId]
    if (!infoList) {
      // 数据空的时候
      let list = []
      list.push(record)
      ChatData.chatInfoMap[chatActiveId] = []
      ChatData.chatInfoMap[chatActiveId] = [...list]
      ChatData.activeChatList.forEach(item2 => {
        if (chatActiveId === item2.chatActiveId && record.sendUserId !== ChatData.userId && ChatData.currentChatId !== chatActiveId) {
          item2.newsNum++
          ChatData.newsNum++
        }
      })
    } else if (record.sendTime > infoList[0].sendTime) {
      // 数据不为空，且是新加数据
      let list = []
      list.push(record)
      list.push(...infoList)
      ChatData.chatInfoMap[chatActiveId] = []
      ChatData.chatInfoMap[chatActiveId] = [...list]
      ChatData.activeChatList.forEach(item2 => {
        if (chatActiveId === item2.chatActiveId && record.sendUserId !== ChatData.userId && ChatData.currentChatId !== chatActiveId) {
          item2.newsNum++
          ChatData.newsNum++
        }
      })
    } else if (record.sendTime >= infoList[infoList.length - 1].sendTime) {
      // 数据不为空，且属于更新数据
      for (let i = 0; i < infoList.length; i++) {
        if (record.recordId === infoList[i].recordId) {
          infoList[i] = record
        }
      }
    } else {
      // 历史数据
      infoList.push(record)
    }
  },
  // 更新活跃聊天室顺序
  updateActiveList (record) {
    let newRecordList = ChatData.chatInfoMap[ChatData.activeChatList[0].chatActiveId]
    if (newRecordList && newRecordList.length > 0 && newRecordList[0].sendTime < record.sendTime) {
      if (ChatData.activeChatList[0].chatActiveId !== record.chatActiveId) {
        let tmpList = []
        tmpList[0] = record
        for (let i = 0; i < ChatData.activeChatList.length; i++) {
          if (ChatData.activeChatList[i].chatActiveId !== record.chatActiveId) {
            tmpList.push(ChatData.activeChatList[i])
          } else {
            tmpList[0] = ChatData.activeChatList[i]
          }
        }
        tmpList[0].newsNum++
        ChatData.newsNum++
        ChatData.activeChatList = []
        ChatData.activeChatList = tmpList
      } else {
        ChatData.activeChatList[0].receiveState = record.receiveState
      }
    }
  },
  checkDate () {
    if (!ChatData.userId) {
      let user = Vue.ls.get(USER_INFO)
      ChatData.accessToken = Vue.ls.get(ACCESS_TOKEN)
      ChatData.infoRandom = user.infoRandom
      ChatData.userId = user.userId
    }
  }
}

export default {
  ChatData
}
